<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书发布测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], 
        input[type="number"], 
        select, 
        textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            min-height: 100px;
            resize: vertical;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 10px;
        }
        button:hover {
            background-color: #45a049;
        }
        .result {
            margin-top: 20px;
            border-top: 1px solid #eee;
            padding-top: 20px;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .loading {
            text-align: center;
            margin: 20px 0;
            display: none;
        }
        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        .status.success {
            background-color: #e8f5e9;
            border: 1px solid #a5d6a7;
            color: #2e7d32;
        }
        .status.error {
            background-color: #ffebee;
            border: 1px solid #ef9a9a;
            color: #c62828;
        }
        .token-input {
            font-family: monospace;
            font-size: 12px;
        }
        .preview-image {
            max-width: 100%;
            max-height: 200px;
            margin: 10px 0;
            border: 1px solid #ddd;
            display: none;
        }
        #paramsPreview {
            margin-top: 20px;
            padding: 10px;
            border: 1px dashed #ccc;
            background-color: #f9f9f9;
            font-family: monospace;
            white-space: pre-wrap;
            display: none;
        }
        .panel-title {
            font-weight: bold;
            margin-bottom: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>图书发布测试</h1>
        
        <div class="form-group">
            <label for="tokenInput">JWT令牌 (Authorization Bearer Token)</label>
            <input type="text" id="tokenInput" class="token-input" placeholder="输入JWT令牌...">
            <small style="display: block; margin-top: 5px; color: #666;">注意：直接输入 JWT 令牌值即可，不需要添加 "Bearer " 前缀</small>
        </div>
        
        <form id="uploadForm">
            <div class="form-group">
                <label for="title">图书标题 *</label>
                <input type="text" id="title" name="title" required placeholder="请输入书名">
            </div>
            
            <div class="form-group">
                <label for="author">作者 *</label>
                <input type="text" id="author" name="author" required placeholder="请输入作者名">
            </div>
            
            <div class="form-group">
                <label for="category">图书分类 *</label>
                <select id="category" name="category" required>
                    <option value="">请选择分类</option>
                    <option value="计算机与编程">计算机与编程</option>
                    <option value="文学与小说">文学与小说</option>
                    <option value="经济管理">经济管理</option>
                    <option value="自然科学">自然科学</option>
                    <option value="医学与健康">医学与健康</option>
                    <option value="社会科学">社会科学</option>
                    <option value="艺术设计">艺术设计</option>
                    <option value="历史">历史</option>
                    <option value="外语学习">外语学习</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="price">价格 (元) *</label>
                <input type="number" id="price" name="price" min="0" step="0.01" required placeholder="请输入价格">
            </div>
            

            
            <div class="form-group">
                <label for="newDegree">新旧程度 (1-100) *</label>
                <input type="number" id="newDegree" name="new_degree" min="1" max="100" required placeholder="请输入新旧程度，1-100">
            </div>
            
            <div class="form-group">
                <label for="description">图书描述 *</label>
                <textarea id="description" name="description" required placeholder="请输入详细描述..."></textarea>
            </div>
            
            <div class="form-group">
                <label for="coverFile">封面图片</label>
                <input type="file" id="coverFile" name="coverFile" accept="image/*">
                <img id="previewImage" class="preview-image" alt="预览图">
            </div>
            
            <button type="button" id="previewBtn">预览参数</button>
            <button type="button" id="submitBtn">发布图书</button>
        </form>
        
        <div id="paramsPreview">
            <div class="panel-title">参数预览（JSON格式）：</div>
            <div id="paramsContent"></div>
        </div>
        
        <div class="loading" id="loadingIndicator">上传中，请稍候...</div>
        
        <div class="result" id="resultContainer">
            <div class="status" id="statusMessage"></div>
            <div id="errorContainer" class="error"></div>
            <div id="apiResponse" class="error" style="white-space: pre-wrap;"></div>
        </div>
    </div>

    <script>
        // 预览图片
        document.getElementById('coverFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const previewImage = document.getElementById('previewImage');
                    previewImage.src = event.target.result;
                    previewImage.style.display = 'block';
                }
                reader.readAsDataURL(file);
            }
        });

        // 构建书籍数据
        function buildBookData() {
            return {
                title: document.getElementById('title').value,
                author: document.getElementById('author').value,
                category: document.getElementById('category').value,
                price: parseFloat(document.getElementById('price').value),
                new_degree: parseInt(document.getElementById('newDegree').value),
                description: document.getElementById('description').value,
                cover: null, // 在预览按钮的事件处理程序中设置
                cover_type: null
            };
        }
        
        // 预览参数
        document.getElementById('previewBtn').addEventListener('click', function() {
            // 表单验证
            const requiredFields = ['title', 'author', 'category', 'price', 'newDegree', 'description'];
            
            for (const field of requiredFields) {
                const element = document.getElementById(field);
                if (!element.value) {
                    alert(`请填写${element.getAttribute('placeholder') || element.previousElementSibling.textContent}`);
                    element.focus();
                    return;
                }
            }
            
            // 构建数据
            const bookData = buildBookData();
            
            // 处理图片
            const fileInput = document.getElementById('coverFile');
            if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                const reader = new FileReader();
                
                reader.onload = function(event) {
                    // 获取Base64数据
                    const base64Data = event.target.result.split(',')[1]; // 移除data:image部分
                    
                    // 添加到书籍数据
                    bookData.cover = base64Data.substring(0, 30) + '... (Base64数据已截断)';
                    bookData.cover_type = file.type;
                    
                    // 显示参数
                    displayParams(bookData);
                };
                
                reader.readAsDataURL(file);
            } else {
                // 无图片
                displayParams(bookData);
            }
        });
        
        // 显示参数
        function displayParams(bookData) {
            const paramsPreview = document.getElementById('paramsPreview');
            const paramsContent = document.getElementById('paramsContent');
            
            // 创建参数类型说明
            let typeInfo = '';
            
            for (const key in bookData) {
                if (bookData.hasOwnProperty(key)) {
                    const value = bookData[key];
                    let type = typeof value;
                    
                    if (key === 'cover') {
                        type = 'string (Base64)';
                    } else if (key === 'cover_type') {
                        type = 'string (MIME类型)';
                    }
                    
                    typeInfo += `${key}: ${type}\n`;
                }
            }
            
            // 显示JSON格式和类型信息
            paramsContent.innerHTML = `<strong>参数值:</strong>\n${JSON.stringify(bookData, null, 2)}\n\n` +
                                     `<strong>参数类型:</strong>\n${typeInfo}`;
            
            paramsPreview.style.display = 'block';
        }

        // 提交表单
        document.getElementById('submitBtn').addEventListener('click', async function() {
            // 表单验证
            const requiredFields = ['title', 'author', 'category', 'price', 'newDegree', 'description'];
            
            for (const field of requiredFields) {
                const element = document.getElementById(field);
                if (!element || !element.value) {
                    alert(`请填写${element ? (element.getAttribute('placeholder') || element.previousElementSibling.textContent) : field}`);
                    if (element) element.focus();
                    return;
                }
            }
            
            // 清空之前的结果
            document.getElementById('errorContainer').textContent = '';
            document.getElementById('statusMessage').className = 'status';
            document.getElementById('statusMessage').textContent = '';
            document.getElementById('apiResponse').textContent = '';
            
            // 显示加载指示器
            document.getElementById('loadingIndicator').style.display = 'block';
            
            // 准备数据
            const bookData = buildBookData();
            
            // 处理图片
            const fileInput = document.getElementById('coverFile');
            if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                const fileReader = new FileReader();
                
                fileReader.onload = async function(event) {
                    try {
                        // 获取Base64数据
                        const base64Data = event.target.result.split(',')[1]; // 移除data:image部分
                        const fileType = file.type;
                        
                        // 添加到书籍数据
                        bookData.cover = base64Data;
                        bookData.cover_type = fileType;
                        
                        // 打印要发送的数据
                        console.log('待发送的数据：', bookData);
                        console.log('数据类型检查：');
                        for (const key in bookData) {
                            console.log(`${key}: ${typeof bookData[key]}`);
                        }
                        
                        // 执行上传
                        await uploadBook(bookData);
                    } catch (error) {
                        handleError(error);
                    }
                };
                
                fileReader.readAsDataURL(file);
            } else {
                // 无图片上传
                try {
                    // 打印要发送的数据
                    console.log('待发送的数据：', bookData);
                    console.log('数据类型检查：');
                    for (const key in bookData) {
                        console.log(`${key}: ${typeof bookData[key]}`);
                    }
                    
                    await uploadBook(bookData);
                } catch (error) {
                    handleError(error);
                }
            }
        });
        
        // 上传图书API调用
        async function uploadBook(bookData) {
            let token = document.getElementById('tokenInput').value.trim();
            if (!token) {
                document.getElementById('errorContainer').textContent = '请输入JWT令牌';
                document.getElementById('loadingIndicator').style.display = 'none';
                return;
            }
            
            // 移除可能已存在的Bearer前缀
            if (token.startsWith('Bearer ')) {
                token = token.substring(7);
            }
            
            try {
                // 将请求体转换为JSON字符串显示在控制台
                const requestBody = JSON.stringify(bookData);
                console.log('请求体JSON字符串：', requestBody);
                
                // 构建请求头
                const headers = {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                };
                
                // 打印请求头
                console.log('请求头：', headers);
                
                const response = await fetch('http://localhost:8080/api/user/book/upload', {
                    method: 'POST',
                    headers: headers,
                    body: requestBody
                });
                
                // 输出HTTP状态码
                console.log('HTTP响应状态码：', response.status);
                
                const textResponse = await response.text();
                console.log('原始响应文本：', textResponse);
                
                // 尝试解析JSON
                let result;
                try {
                    result = JSON.parse(textResponse);
                    console.log('解析后响应数据：', result);
                } catch (e) {
                    console.error('解析响应JSON失败：', e);
                    result = { message: '无法解析服务器响应' };
                }
                
                // 隐藏加载指示器
                document.getElementById('loadingIndicator').style.display = 'none';
                
                // 显示完整API响应
                document.getElementById('apiResponse').textContent = '服务器响应：\n' + JSON.stringify(result, null, 2);
                
                if (result.code === 200) {
                    // 成功
                    document.getElementById('statusMessage').className = 'status success';
                    document.getElementById('statusMessage').textContent = result.message || '图书发布成功';
                    
                    // 如果需要，显示返回的书籍ID
                    if (result.data && result.data.bookId) {
                        document.getElementById('statusMessage').textContent += ` (ID: ${result.data.bookId})`;
                    }
                    
                    // 清空表单
                    document.getElementById('uploadForm').reset();
                    document.getElementById('previewImage').style.display = 'none';
                    document.getElementById('paramsPreview').style.display = 'none';
                } else {
                    // 请求失败
                    document.getElementById('statusMessage').className = 'status error';
                    document.getElementById('statusMessage').textContent = result.message || '图书发布失败';
                }
            } catch (error) {
                handleError(error);
            }
        }
        
        function handleError(error) {
            console.error('Error:', error);
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('errorContainer').textContent = `错误: ${error.message}`;
        }
    </script>
</body>
</html> 